package com.demo.config.shiro;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.commons.utils.Shiro2Utils;
import com.demo.sys.entity.SysUserEntity;
import com.demo.sys.service.SysMenuService;
import com.demo.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 认证
 *@author zwy
 *@date 2023/8/10 2:11
*/
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取到用户实体类
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        String type = user.getType();
        Long groupId = user.getGroupId();
        List<String> permsList = new ArrayList<>();
        //系统管理员，拥有最高权限
        if (Integer.valueOf(type) == 0) {
            //超级管理员
            //TODO：缺少sm.is_del = 0 and在sysmenudao
            permsList = sysMenuService.getPermsList(type);
        }else{
            //其它管理员
            permsList = sysMenuService.getPermsList(groupId.toString());
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }


    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        System.out.println("sss="+token.getUsername());
        //查询用户信息
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("account", token.getUsername())
                .eq("is_del", 0));
        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        if ("1".equals(user.getStatus())) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        System.out.println(user+"=============");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        //密码加密 类型
        shaCredentialsMatcher.setHashAlgorithmName(Shiro2Utils.HASH_ALGORITHM_NAME_SHA256);
        shaCredentialsMatcher.setHashIterations(Shiro2Utils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
